<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="物料类型" prop="itemTypeName" >
        <el-input
          v-model="queryParams.itemTypeName"
          placeholder="请输入产品物料类型名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['type:type:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Sort"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="typeList"
      row-key="itemTypeId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="产品物料类型名称" align="center" prop="itemTypeName" />
      <el-table-column label="产品/物料" align="center" prop="itemOrProduct" />
      <el-table-column label="排列顺序" align="center" prop="orderNum" />
      <el-table-column label="是否启用" align="center" prop="enableFlag" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['type:type:add']">新增</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['type:type:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['type:type:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改物料分类对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="typeRef" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="产品物料类型编码" prop="itemTypeCode">
          <el-input style="width: 600px;" v-model="form.itemTypeCode" placeholder="请输入产品物料类型编码" :disabled="value1"/>
          <span v-if="autoNumber" style="margin-left: 10px; white-space: nowrap;">
              <el-switch v-model="value1" @change="handleChange" /> 自动生成
            </span>
        </el-form-item>
        <el-form-item label="产品物料类型名称" prop="itemTypeName">
          <el-input v-model="form.itemTypeName" placeholder="请输入产品物料类型名称" />
        </el-form-item>
        <el-form-item label="父类型ID" prop="parentTypeId">
          <el-tree-select
            v-model="form.parentTypeId"
            :data="typeOptions"
            :props="{ value: 'itemTypeId', label: 'itemTypeName', children: 'children' }"
            value-key="itemTypeId"
            placeholder="请选择父类型ID"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="产品/物料" prop="itemOrProduct">
          <el-select 
            v-model="form.itemOrProduct" 
            placeholder="请选择产品/物料" 
            style="width: 100%"
          >
            <!-- 固定选项：第一个“物料”，第二个“产品” -->
            <el-option label="产品" value="产品"></el-option>
            <el-option label="物料" value="物料"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排列顺序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入排列顺序" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Type">
import { listType, getType, delType, addType, updateType } from "@/api/type/type"
const value1 = ref(false)
function handleChange(value) {
  if (value) {
    form.value.itemTypeCode = 'PR' + new Date().getTime()
  } else {
    form.value.itemTypeCode = ''
  }
}
const { proxy } = getCurrentInstance()
const autoNumber = ref(true)//自动生成工单编号按钮是否显示
const typeList = ref([])
const typeOptions = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const title = ref("")
const isExpandAll = ref(true)
const refreshTable = ref(true)

const data = reactive({
  form: {},
  queryParams: {
    itemTypeName: null,
    enableFlag: null,
  },
  rules: {
    itemTypeCode: [
      { required: true, message: "产品物料类型编码不能为空", trigger: "blur" }
    ],
    itemTypeName: [
      { required: true, message: "产品物料类型名称不能为空", trigger: "blur" }
    ],
    parentTypeId: [
      { required: true, message: "父类型ID不能为空", trigger: "blur" }
    ],
    ancestors: [
      { required: true, message: "所有层级父节点不能为空", trigger: "blur" }
    ],
    itemOrProduct: [
      { required: true, message: "产品/物料不能为空", trigger: "blur" }
    ],
    enableFlag: [
      { required: true, message: "是否启用不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询物料分类列表 */
function getList() {
  loading.value = true
  listType(queryParams.value).then(response => {
    typeList.value = proxy.handleTree(response.data, "itemTypeId", "parentTypeId")
    loading.value = false
  })
}

/** 查询物料分类下拉树结构 */
function getTreeselect() {
  listType().then(response => {
    typeOptions.value = []
    const data = { itemTypeId: 0, itemTypeName: '顶级节点', children: [] }
    data.children = proxy.handleTree(response.data, "itemTypeId", "parentTypeId")
    typeOptions.value.push(data)
  })
}
	
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    itemTypeId: null,
    itemTypeCode: null,
    itemTypeName: null,
    parentTypeId: null,
    ancestors: null,
    itemOrProduct: null,
    orderNum: null,
    enableFlag: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("typeRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset()
  getTreeselect()
  if (row != null && row.itemTypeId) {
    form.value.parentTypeId = row.itemTypeId
  } else {
    form.value.parentTypeId = 0
  }
  open.value = true
  title.value = "添加物料分类"
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset()
  await getTreeselect()
  if (row != null) {
    form.value.parentTypeId = row.parentTypeId
  }
  getType(row.itemTypeId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改物料分类"
  })
}


/**
 * 根据父节点ID获取所有祖先节点ID
 */
function getAncestors(parentId, tree = typeOptions.value, ancestors = []) {
  if (parentId === 0 || parentId === null) {
    return ancestors.join(',');
  }
  
  for (const node of tree) {
    if (node.itemTypeId === parentId) {
      ancestors.unshift(node.itemTypeId);
      return getAncestors(node.parentTypeId, typeOptions.value, ancestors);
    }
    if (node.children && node.children.length > 0) {
      const result = getAncestors(parentId, node.children, ancestors);
      if (result) {
        return result;
      }
    }
  }
  return ancestors.join(',');
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["typeRef"].validate(valid => {
    if (valid) {
    // 计算ancestors字段的值
      form.value.ancestors = getAncestors(form.value.parentTypeId);
      if (form.value.itemTypeId != null) {
        updateType(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addType(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除物料分类编号为"' + row.itemTypeId + '"的数据项？').then(function() {
    return delType(row.itemTypeId)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

getList()
</script>
